Popular Searches
Popular Course Categories
Popular Courses

Dart Syntax and Program Structure

Dart Syntax and Program Structure

Introduction to Dart

Dart Syntax and Program Structure

Dart is the programming language used with Flutter to build modern applications. Understanding Dart syntax and program structure is an important foundation before working with Flutter widgets, UI development, APIs, Firebase, state management, and complete mobile applications.

JustAcademy's Flutter Training includes Dart language fundamentals as an early part of the curriculum. The course covers variables, data types, operators, control statements, functions and parameters, object-oriented programming, collections, and asynchronous programming with Future and async/await. :contentReference[oaicite:0]{index=0} 

Explore JustAcademy's Flutter Training

Register for Flutter Course Demo


1. What is Dart Syntax?

Dart syntax refers to the rules and structure used to write valid Dart programs. It defines how variables, functions, classes, statements, expressions, comments, operators, and other programming elements are written.

A Dart program follows a structured syntax that makes the code readable and organized.

Basic Dart Example

void main() {
  String name = "Amit";
  int age = 25;

  print("Name: $name");
  print("Age: $age");
}

This simple program contains a main() function, variable declarations, statements, and output using print().


2. Basic Structure of a Dart Program

A simple Dart program can be organized into several parts:

  1. Comments
  2. Imports
  3. Variables and constants
  4. Functions
  5. Classes
  6. The main() function
  7. Statements and expressions

Example

// Import section
import 'dart:math';

// Function
int calculateSquare(int number) {
  return number * number;
}

// Main function
void main() {
  int value = 5;

  print(calculateSquare(value));
}

Dart allows developers to divide application functionality into reusable functions, classes, and other program components.


3. The main() Function

The main() function is the starting point of a Dart program. When a Dart application is executed, program execution begins from the main() function.

Basic main() Function

void main() {
  print("Hello Dart");
}

Here:

  • void indicates that the function does not return a value.
  • main is the function name.
  • () contains the function parameters.
  • { } contains the statements executed by the function.

main() with Variables

void main() {
  String course = "Flutter";
  int duration = 3;

  print(course);
  print(duration);
}

main() with Arguments

void main(List arguments) {
  print(arguments);
}

The parameterized form can receive command-line arguments when a Dart application is executed in an environment that provides them.


4. Dart Statements

A statement is an instruction that tells the program to perform an operation. Many Dart statements end with a semicolon ;.

Variable Declaration

String name = "Rahul";

Assignment Statement

int age = 20;

age = 21;

Function Call Statement

print("Hello Dart");

Conditional Statement

if (age >= 18) {
  print("Adult");
}

Loop Statement

for (int i = 1; i <= 5; i++) {
  print(i);
}

5. Semicolons in Dart

Dart commonly uses a semicolon ; to mark the end of a statement.

String name = "Amit";
int age = 25;

print(name);
print(age);

Semicolons help separate individual statements and make the structure of the program clear.

Example of Multiple Statements

void main() {
  int a = 10;
  int b = 20;
  int sum = a + b;

  print(sum);
}

6. Dart Comments

Comments are text written inside source code to explain the program. Comments are ignored when the program executes.

Dart supports single-line comments, multi-line comments, and documentation comments.

6.1 Single-Line Comments

A single-line comment begins with //.

// This is a single-line comment

void main() {
  // Display a message
  print("Hello Dart");
}

6.2 Multi-Line Comments

Multi-line comments begin with /* and end with */.

/*
  This is a multi-line comment.
  It can contain multiple lines.
*/

void main() {
  print("Hello Dart");
}

6.3 Documentation Comments

Documentation comments can be written using ///. They are useful for documenting classes, functions, methods, and other program elements.

/// Calculates the sum of two numbers.
int add(int a, int b) {
  return a + b;
}

7. Variables in Dart Syntax

Variables are used to store values that an application needs to work with.

Explicit Type Declaration

String name = "Amit";
int age = 25;
double salary = 45000.50;
bool isActive = true;

Using var

var name = "Amit";
var age = 25;
var price = 499.99;

Dart can infer the type of a variable from its assigned value when var is used.

Using dynamic

dynamic value = "Dart";

value = 100;
value = true;

dynamic allows a variable to hold values of different types, but it should be used carefully because it provides less compile-time type information.


8. Constants in Dart

Dart provides final and const for values that should not be reassigned.

final

final String name = "Flutter";

A final variable can be assigned once.

const

const double pi = 3.14159;

A const value represents a compile-time constant.


9. Data Types and Syntax

Dart supports several commonly used data types.

Data Type Purpose Example
int Whole numbers int age = 25;
double Decimal numbers double price = 99.50;
num Integer or decimal numbers num value = 10.5;
String Text String name = "Amit";
bool True or false bool active = true;
List Ordered collection List names
Set Unique values Set numbers
Map Key-value collection Map

10. String Syntax

Strings are used to represent text in Dart. Single or double quotes can be used for ordinary strings.

String name = "Amit";
String city = 'Mumbai';

String Interpolation

String name = "Amit";
int age = 25;

print("My name is $name");
print("My age is $age");

Expression Interpolation

int price = 500;
int quantity = 2;

print("Total: ${price * quantity}");

Multi-Line String

String message = '''
Welcome to Dart.
Learn Dart before Flutter.
Build modern applications.
''';

print(message);

11. Operators in Dart Syntax

Operators are symbols used to perform calculations, comparisons, assignments, and logical operations.

Arithmetic Operators

int a = 10;
int b = 3;

print(a + b);
print(a - b);
print(a * b);
print(a / b);
print(a % b);

Comparison Operators

int age = 20;

print(age == 20);
print(age != 18);
print(age > 18);
print(age < 30);

Logical Operators

bool hasEmail = true;
bool hasPassword = true;

print(hasEmail && hasPassword);
print(hasEmail || hasPassword);
print(!hasEmail);

Assignment Operators

int count = 10;

count += 5;
count -= 2;
count *= 2;

12. Expressions in Dart

An expression is a piece of code that produces a value.

int result = 10 + 20;

Here, 10 + 20 is an expression that produces the value 30.

More Examples

int total = price * quantity;

bool isAdult = age >= 18;

String message = "Hello " + name;

13. Conditional Statements

Conditional statements allow a program to execute different code depending on a condition.

if Statement

int age = 20;

if (age >= 18) {
  print("Adult");
}

if-else Statement

int age = 16;

if (age >= 18) {
  print("Adult");
} else {
  print("Minor");
}

else-if Statement

int marks = 75;

if (marks >= 90) {
  print("Excellent");
} else if (marks >= 60) {
  print("Good");
} else {
  print("Needs improvement");
}

Control statements such as if are part of the Dart programming fundamentals included in JustAcademy's Flutter curriculum. :contentReference[oaicite:1]{index=1} 


14. switch Statement

A switch statement can be used when different actions need to be performed based on the value of an expression.

String day = "Monday";

switch (day) {
  case "Monday":
    print("Start of the week");
    break;

  case "Friday":
    print("End of the work week");
    break;

  default:
    print("Regular day");
}

15. Loops in Dart

Loops are used to execute a block of code repeatedly.

for Loop

for (int i = 1; i <= 5; i++) {
  print(i);
}

while Loop

int i = 1;

while (i <= 5) {
  print(i);
  i++;
}

do-while Loop

int i = 1;

do {
  print(i);
  i++;
} while (i <= 5);

for-in Loop

List names = [
  "Amit",
  "Rahul",
  "Priya"
];

for (String name in names) {
  print(name);
}

16. Functions in Dart

Functions are reusable blocks of code that perform a specific task.

Basic Function

void greet() {
  print("Hello Dart");
}

void main() {
  greet();
}

Function with Parameters

void greetUser(String name) {
  print("Hello $name");
}

void main() {
  greetUser("Amit");
}

Function with Return Value

int add(int a, int b) {
  return a + b;
}

void main() {
  int result = add(10, 20);

  print(result);
}

Functions and parameters are included in the Dart programming fundamentals covered by JustAcademy's Flutter curriculum. :contentReference[oaicite:2]{index=2} 


17. Arrow Functions

Dart supports concise function syntax using the arrow operator =>.

int square(int number) => number * number;

void main() {
  print(square(5));
}

Arrow functions are useful for short functions containing a single expression.


18. Named Parameters

Named parameters allow function arguments to be provided using their parameter names.

void createUser({
  required String name,
  required int age,
}) {
  print("Name: $name");
  print("Age: $age");
}

void main() {
  createUser(
    name: "Amit",
    age: 25,
  );
}

Named parameters can make function calls more descriptive and are widely encountered when working with Flutter widget constructors.


19. Optional Parameters

Dart supports optional positional and named parameters.

Optional Positional Parameter

void greet(String name, [String? city]) {
  print("Name: $name");

  if (city != null) {
    print("City: $city");
  }
}

void main() {
  greet("Amit");
  greet("Rahul", "Mumbai");
}

Optional Named Parameter

void showUser({
  String name = "Guest",
  int age = 0,
}) {
  print(name);
  print(age);
}

20. Classes and Objects

Dart is an object-oriented programming language. Classes can be used to define the structure and behavior of objects.

class Student {
  String name;
  int age;

  Student(this.name, this.age);

  void display() {
    print("Name: $name");
    print("Age: $age");
  }
}

void main() {
  Student student = Student("Amit", 21);

  student.display();
}

JustAcademy's curriculum includes classes, objects, constructors, inheritance, polymorphism, and abstraction within Dart programming fundamentals. :contentReference[oaicite:3]{index=3} 


21. Constructors

Constructors are used to initialize objects when they are created.

class Product {
  String name;
  double price;

  Product(this.name, this.price);
}

void main() {
  Product product = Product("Laptop", 55000);

  print(product.name);
  print(product.price);
}

Named Constructor Parameters

class Product {
  final String name;
  final double price;

  Product({
    required this.name,
    required this.price,
  });
}

void main() {
  Product product = Product(
    name: "Laptop",
    price: 55000,
  );

  print(product.name);
}

22. Lists in Dart

A List stores multiple values in an ordered collection.

List fruits = [
  "Apple",
  "Banana",
  "Mango"
];

print(fruits[0]);
print(fruits.length);

Adding an Item

fruits.add("Orange");

Removing an Item

fruits.remove("Banana");

List collections are part of the Dart fundamentals included in JustAcademy's Flutter curriculum. :contentReference[oaicite:4]{index=4} 


23. Sets in Dart

A Set is a collection designed for unique values.

Set skills = {
  "Dart",
  "Flutter",
  "Firebase"
};

skills.add("API");

24. Maps in Dart

A Map stores data in key-value pairs.

Map user = {
  "name": "Amit",
  "age": 25,
  "active": true
};

print(user["name"]);

List, Set, and Map collections are specifically included in the Dart programming fundamentals of JustAcademy's Flutter course. :contentReference[oaicite:5]{index=5} 


25. Import Statements

The import statement allows a Dart file to use libraries and functionality defined elsewhere.

Importing a Dart Library

import 'dart:math';

void main() {
  print(sqrt(25));
}

Importing a Flutter Package

import 'package:flutter/material.dart';

In Flutter applications, imports are commonly used to access Flutter widgets and other packages.


26. Program Structure Using Multiple Files

A larger application should not place all code into one file. Dart allows developers to divide functionality into multiple files.

Example Project Structure

lib/
├── main.dart
├── models/
│   └── user.dart
├── services/
│   └── api_service.dart
├── screens/
│   └── home_screen.dart
└── widgets/
    └── user_card.dart

A possible responsibility for each area is:

  • main.dart: Application entry point.
  • models: Data models and classes.
  • services: API and external-service logic.
  • screens: Application screens.
  • widgets: Reusable UI components.

JustAcademy's Flutter curriculum introduces project structure during the Flutter introduction module and later covers app structure, API integration, state management, and real-world project development. :contentReference[oaicite:6]{index=6} 


27. Asynchronous Program Structure

Dart supports asynchronous programming using Future, async, and await.

Future fetchUser() async {
  await Future.delayed(
    Duration(seconds: 2),
  );

  return "Amit";
}

void main() async {
  print("Loading...");

  String user = await fetchUser();

  print("User: $user");
}

JustAcademy's Dart fundamentals include asynchronous programming using Future and async/await. :contentReference[oaicite:7]{index=7} 


28. Exception Handling Syntax

Dart provides try, catch, finally, and throw for handling exceptions.

void main() {
  try {
    int result = 10 ~/ 0;

    print(result);
  } catch (error) {
    print("Error: $error");
  } finally {
    print("Finished");
  }
}

Throwing an Exception

void validateAge(int age) {
  if (age < 18) {
    throw Exception("Age must be 18 or above");
  }

  print("Valid age");
}

29. Complete Dart Program Example

The following example combines several basic Dart syntax and program-structure concepts.

import 'dart:math';

class Student {
  final String name;
  final int marks;

  Student({
    required this.name,
    required this.marks,
  });

  void displayResult() {
    if (marks >= 40) {
      print("$name has passed.");
    } else {
      print("$name has failed.");
    }
  }
}

int calculateBonus(int marks) {
  return marks + 5;
}

void main() {
  List students = [
    Student(
      name: "Amit",
      marks: 75,
    ),
    Student(
      name: "Priya",
      marks: 35,
    ),
  ];

  for (Student student in students) {
    student.displayResult();

    int updatedMarks = calculateBonus(student.marks);

    print("Updated Marks: $updatedMarks");
  }

  print("Random Number: ${Random().nextInt(100)}");
}

Concepts Used

  • Import statement
  • Class
  • Constructor
  • final variables
  • Named parameters
  • List
  • Function
  • if-else condition
  • for-in loop
  • String interpolation
  • main() function

30. Common Dart Syntax Rules

Rule Example
Statements generally end with a semicolon print("Hello");
Code blocks use curly braces if (condition) { }
Variables can have explicit types int age = 25;
Type inference is available var age = 25;
Single-line comments use // // Comment
Multi-line comments use /* */ /* Comment */
Functions use parentheses print("Hello");
Classes use the class keyword class Student { }
Imports use the import keyword import 'dart:math';
Entry point is main() void main() { }

31. Best Practices for Dart Program Structure

  • Use meaningful variable and function names.
  • Keep functions focused on a specific responsibility.
  • Use classes to organize related data and behavior.
  • Divide large applications into multiple files.
  • Use comments when they provide useful context.
  • Use appropriate data types instead of relying unnecessarily on dynamic.
  • Use null safety features correctly.
  • Keep business logic separate from UI code when building larger Flutter applications.
  • Use reusable functions and components instead of duplicating code.
  • Use consistent formatting and indentation.

32. Dart Syntax vs Flutter Syntax

Dart is the programming language, while Flutter provides the framework and widget system used to build the application interface.

Dart Flutter
Variables Widget properties and application state
Functions Widget methods and callbacks
Classes Widgets, models, services, controllers
List / Set / Map Application and UI data
Future / async / await API and asynchronous application operations
Exception handling Error handling in application operations
String interpolation Dynamic text in UI

33. Quick Revision

Topic Key Point
Dart Syntax Rules used to write valid Dart programs.
main() Entry point of a Dart application.
Statements Instructions executed by the program.
Comments Notes that are ignored during execution.
Variables Store application data.
Functions Reusable blocks of code.
Classes Blueprints for objects.
Collections List, Set, and Map store groups of data.
Conditions Control which code executes.
Loops Repeat code multiple times.
Imports Make libraries and packages available.
Future Represents an asynchronous result.
async/await Helps structure asynchronous code.

34. Key Takeaways

  • Dart syntax defines the rules for writing Dart programs.
  • The main() function is the entry point of a Dart application.
  • Statements represent instructions executed by the program.
  • Semicolons are commonly used to terminate Dart statements.
  • Comments can be used to document and explain code.
  • Variables store application data.
  • Functions provide reusable blocks of logic.
  • Classes and objects support object-oriented programming.
  • List, Set, and Map are important Dart collection types.
  • Conditions and loops control program execution.
  • Imports allow developers to use libraries and packages.
  • Future, async, and await are important for asynchronous programming.
  • Organizing Dart code into functions, classes, and separate files makes larger applications easier to maintain.
  • Understanding Dart syntax provides a foundation for learning Flutter development.

35. Learn Dart and Flutter with JustAcademy

JustAcademy's Flutter Training introduces Dart programming fundamentals and then progresses into Flutter widgets, UI development, navigation, API integration, Firebase, state management, testing, deployment, and practical application projects. :contentReference[oaicite:8]{index=8} 

Visit JustAcademy Flutter Training

Register for Flutter Course Demo

Conclusion

Understanding Dart syntax and program structure is an important first step toward Flutter development. Developers should become comfortable with the main() function, statements, comments, variables, data types, operators, conditions, loops, functions, classes, constructors, collections, imports, and asynchronous programming.

Once these fundamentals are understood, developers can use the same Dart concepts while building Flutter widgets, screens, models, services, API integrations, and complete mobile applications. JustAcademy's current Flutter curriculum places Dart programming fundamentals before the broader Flutter widget and UI-development topics. :contentReference[oaicite:9]{index=9} 

whatsapp